/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.transport.session.head;

import com.inyourcode.core.transport.api.payload.BytesHolder;
import com.inyourcode.core.transport.session.BasicTcpAcceptor;
import com.inyourcode.core.transport.session.MessageCoderFactory;
import com.inyourcode.core.transport.session.ResponseContext;
import com.inyourcode.core.transport.session.api.IMessageCoder;
import com.inyourcode.core.transport.session.api.MessageHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author JackLei
 */
public class MessageHeadEncoder extends MessageToMessageEncoder<MessageHolder> {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageHeadEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, MessageHolder responseContext, List<Object> out) throws Exception {

        byte serializerCode = responseContext.getSerializerCode();
        long invokeId = responseContext.getInvokeId();
        IMessageCoder messageCoder = MessageCoderFactory.getMessageCoder(serializerCode);
        if (messageCoder == null) {
            String err = String.format("protocol parser not found, invokeId: %s, : serializerCode: %s", invokeId, serializerCode);
            LOGGER.error(err);
            throw new NullPointerException(err);
        }

        BytesHolder writeBytes = messageCoder.encode(responseContext);
        if (writeBytes == null) {
            String err = String.format("protocol encode fail,  invokeId: %s, : serializerCode: %s", invokeId, serializerCode);
            LOGGER.error(err);
            throw new NullPointerException(err);
        }

        out.add(writeBytes);
    }
}
